package de.hska.pwmanager.controller.aspects;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import de.hska.pwmanager.controller.LoginController;
import de.hska.pwmanager.persistence.model.User.Role;

@Controller
@Aspect
public class SecurityAspect {
	@Autowired
	private LoginController loginController;
	private boolean activeAuth = true;

	public void setActiveAuth(boolean activeAuth) {
		this.activeAuth = activeAuth;
	}

	@Around("execution(* de.hska.pwmanager.controller.IPasswordCategoryController.*(..))")
	public Object checkIPasswordCategoryController(ProceedingJoinPoint joinPoint)
			throws Throwable {
		return this.checkAdminAccess(joinPoint);
	}

	@Around("execution(* de.hska.pwmanager.controller.IPasswordController.*(..))")
	public Object checkIPasswordController(ProceedingJoinPoint joinPoint)
			throws Throwable {
		return this.checkUserAuth(joinPoint);
	}

	@Around("execution(* de.hska.pwmanager.controller.IUserController.*(..))")
	public Object checkIUserController(ProceedingJoinPoint joinPoint)
			throws Throwable {
		return this.checkAdminAccess(joinPoint);
	}

	private Object checkAdminAccess(ProceedingJoinPoint joinPoint)
			throws Throwable {
		if (this.activeAuth
				&& (loginController.getLoggedInUser() == null || this.loginController
						.getLoggedInUser().getRole() != Role.ADMINISTRATOR)) {
			System.out.println("unauthorized access");
			return null;
		} else {
			return joinPoint.proceed();
		}
	}

	private Object checkUserAuth(ProceedingJoinPoint joinPoint)
			throws Throwable {
		if (this.activeAuth && loginController.getLoggedInUser() == null) {
			System.out.println("unauthorized access");
			return null;
		} else {
			Object retVal = joinPoint.proceed();
			return retVal;
		}
	}

	public SecurityAspect() {
		System.out.println("Instantiated Security aspect");
	}
}
